import csv
import json
import os
import time
from datetime import datetime, timedelta


# 定义拥堵等级映射，用于比较拥堵程度
congestion_level_mapping = {
    "轻度拥堵": 1,
    "中度拥堵": 2,
    "严重拥堵": 3
}


def split_time_intervals(data_list, threshold=600):
    if not data_list:
        return []
    intervals = []
    current_interval = [data_list[0]]

    for i in range(1, len(data_list)):
        # 将时间字符串转换为 datetime 对象
        current_time = datetime.strptime(data_list[i]["时间"], "%Y-%m-%dT%H:%M:%S.%f")
        prev_time = datetime.strptime(data_list[i - 1]["时间"], "%Y-%m-%dT%H:%M:%S.%f")
        # 计算时间差（秒）
        time_diff = (current_time - prev_time).total_seconds()
        if time_diff > threshold:
            # 如果时间差超过阈值，开始一个新的区间
            intervals.append(current_interval)
            current_interval = [data_list[i]]
        else:
            # 否则，将当前数据添加到当前区间
            current_interval.append(data_list[i])

    # 添加最后一个区间
    intervals.append(current_interval)

    result = []
    for interval in intervals:
        # 找出区间内路况的最高拥堵等级
        max_congestion_level = max(congestion_level_mapping[item["路况"]] for item in interval)
        # 根据最大等级值找到对应的路况描述
        max_congestion_status = [k for k, v in congestion_level_mapping.items() if v == max_congestion_level][0]

        start_time = datetime.strptime(interval[0]["时间"], "%Y-%m-%dT%H:%M:%S.%f")
        if len(interval) == 1:
            # 如果区间只有一个时间，加上 15 秒作为结束时间
            end_time = start_time + timedelta(seconds=300)
        else:
            end_time = datetime.strptime(interval[-1]["时间"], "%Y-%m-%dT%H:%M:%S.%f")

        result.append({
            "start_time": start_time.strftime("%Y-%m-%d %H:%M:%S"),
            "end_time": end_time.strftime("%Y-%m-%d %H:%M:%S"),
            "interval": interval,
            "max_congestion_status": max_congestion_status
        })
    return result


def split_event_time_intervals(data_list, threshold=200):
    if not data_list:
        return []
    intervals = []
    current_interval = [data_list[0]]

    for i in range(1, len(data_list)):
        # 将时间字符串转换为 datetime 对象
        current_time = datetime.strptime(data_list[i]["时间"], "%Y-%m-%dT%H:%M:%S.%f")
        prev_time = datetime.strptime(data_list[i - 1]["时间"], "%Y-%m-%dT%H:%M:%S.%f")
        # 计算时间差（秒）
        time_diff = (current_time - prev_time).total_seconds()
        if time_diff > threshold:
            # 如果时间差超过阈值，开始一个新的区间
            intervals.append(current_interval)
            current_interval = [data_list[i]]
        else:
            # 否则，将当前数据添加到当前区间
            current_interval.append(data_list[i])

    # 添加最后一个区间
    intervals.append(current_interval)

    result = []
    for interval in intervals:
        start_time = datetime.strptime(interval[0]["时间"], "%Y-%m-%dT%H:%M:%S.%f")
        if len(interval) == 1:
            # 如果区间只有一个时间，加上 15 秒作为结束时间
            end_time = start_time + timedelta(seconds=60)
        else:
            end_time = datetime.strptime(interval[-1]["时间"], "%Y-%m-%dT%H:%M:%S.%f")

        result.append({
            "start_time": start_time.strftime("%Y-%m-%d %H:%M:%S"),
            "end_time": end_time.strftime("%Y-%m-%d %H:%M:%S"),
            "interval": interval
        })
    return result


def a(file, dir_path):
    json_path = os.path.join(dir_path, file.split('.')[0] + '.csv')
    if os.path.exists(json_path):
        dict_list = []
        try:
            with open(json_path, mode='r', encoding='utf-8', newline='') as csvfile:
                # 创建 DictReader 对象
                reader = csv.DictReader(csvfile)
                # 逐行读取并转换为字典
                for row in reader:
                    dict_list.append(row)
        except FileNotFoundError:
            print(f"文件 {json_path} 未找到。")
        except Exception as e:
            print(f"读取文件时出现错误: {e}")
        event_list = []
        yongdu_list = []
        for row in dict_list:
            if row['路况'] != '畅通':
                yongdu_list.append({"时间": row["时间"], "路况": row["路况"]})
            if row['事故'] != '畅通':
                event_list.append({"时间": row["时间"], "事故": row["事故"]})

        yongdu_result = split_time_intervals(yongdu_list)
        event_result = split_event_time_intervals(event_list)

        # print(yongdu_result)

        # print(event_result)

        return yongdu_result, event_result


def main():
    folder_path = r"/home/gj/Download/新建文件夹/111"
    log_folder_path = r"C:\Users\wanji\Desktop\fsdownload\2025-02-20_03-06-00"
    # 遍历文件夹及其子文件夹
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.json'):
                json_path = os.path.join(root, file)
                yongdu_result, event_result = a(file, log_folder_path)
                with open(json_path, mode='r', encoding='utf-8', newline='') as json_file:
                    json_data = json.load(json_file)
                    json_data["algorithmValue"] = []
                    direction = "上行"
                    if json_data["truthValue"]:
                        direction = json_data["truthValue"]["direction"]
                    for yongdu in yongdu_result:
                        ddict = {
                            "startTime": yongdu["start_time"],
                            "endTime": yongdu["end_time"],
                            "direction": direction,
                            "eventType": "拥堵",
                            "level": int(congestion_level_mapping[yongdu["max_congestion_status"]])
                        }
                        json_data["algorithmValue"].append(ddict)
                    for event in event_result:
                        # todo
                        level = 0
                        start_time = datetime.strptime(event["start_time"], "%Y-%m-%d %H:%M:%S")
                        end_time = datetime.strptime(event["end_time"], "%Y-%m-%d %H:%M:%S")
                        dt = (end_time - start_time).total_seconds()
                        if dt < 120:
                            level = 1
                        elif dt < 600:
                            level = 2
                        elif dt < 1800:
                            level = 3
                        elif dt < 3600:
                            level = 4
                        else:
                            level = 5
                        ddict = {
                            "startTime": event["start_time"],
                            "endTime": event["end_time"],
                            "direction": direction,
                            "eventType": "阻断",
                            "level": level
                        }
                        json_data["algorithmValue"].append(ddict)


def main1():
    folder_path = r"D:\GJ\项目\事故检测\output0220\algorithm\V1.0"
    log_folder_path = r"D:\GJ\项目\事故检测\logg\2025-02-21_12-07-44"
    new_folder_path = r"D:\GJ\项目\事故检测\output0220 - 副本\algorithm\V6.0"
    if not os.path.exists(new_folder_path):
        os.makedirs(new_folder_path)
    # 遍历文件夹及其子文件夹
    for root, dirs, files in os.walk(log_folder_path):
        for file in files:
            if file.endswith('.csv'):
                yongdu_result, event_result = a(file, log_folder_path)
                json_path = os.path.join(folder_path, file.split('.')[0] + '.json')
                new_json_path = os.path.join(new_folder_path, file.split('.')[0] + '.json')
                with open(json_path, mode='r', encoding='utf-8', newline='') as json_file:
                    json_data = json.load(json_file)
                    json_data["algorithmValue"] = []
                    direction = "上行"
                    if json_data["truthValue"]:
                        direction = json_data["truthValue"][0]["direction"]
                    for yongdu in yongdu_result:
                        ddict = {
                            "startTime": yongdu["start_time"],
                            "endTime": yongdu["end_time"],
                            "direction": direction,
                            "eventType": "拥堵",
                            "level": int(congestion_level_mapping[yongdu["max_congestion_status"]])
                        }
                        json_data["algorithmValue"].append(ddict)
                    for event in event_result:
                        # todo
                        level = 0
                        start_time = datetime.strptime(event["start_time"], "%Y-%m-%d %H:%M:%S")
                        end_time = datetime.strptime(event["end_time"], "%Y-%m-%d %H:%M:%S")
                        dt = (end_time - start_time).total_seconds()
                        if dt < 300:
                            level = 1
                        elif dt < 600:
                            level = 2
                        elif dt < 1800:
                            level = 3
                        elif dt < 3600:
                            level = 4
                        else:
                            level = 5
                        ddict = {
                            "startTime": event["start_time"],
                            "endTime": event["end_time"],
                            "direction": direction,
                            "eventType": "阻断",
                            "level": level
                        }
                        json_data["algorithmValue"].append(ddict)

                    with open(new_json_path, mode='w', encoding='utf-8', newline='') as f:
                        print(new_json_path)
                        json.dump(json_data, f, ensure_ascii=False)


def main2():
    # 存放新的readme.json文件，其内部为算法检测结果数据
    json_path = r"D:\GJ\项目\事故检测\output0305_3\algorithm\V2.6\readme.json"
    # log_folder_path中有所有的检测时保存的csv文件，遍历其中的csv文件获取事件的时间数据
    log_folder_path = r"D:\GJ\项目\事故检测\output0311\0320\save_csv"
    with open(json_path, mode='w', encoding='utf-8', newline='') as f:
        # 遍历文件夹及其子文件夹
        for root, dirs, files in os.walk(log_folder_path):
            for file in files:
                if file.endswith('.csv'):
                    yongdu_result, event_result = a(file, log_folder_path)
                    json_data = {}
                    json_data["id"] = file.split('.')[0]
                    json_data["algorithmValue"] = []
                    direction = "上行"
                    for yongdu in yongdu_result:
                        ddict = {
                            "startTime": yongdu["start_time"],
                            "endTime": yongdu["end_time"],
                            "direction": direction,
                            "eventType": "拥堵",
                            "level": int(congestion_level_mapping[yongdu["max_congestion_status"]])
                        }
                        json_data["algorithmValue"].append(ddict)
                    for event in event_result:
                        # todo
                        level = 0
                        start_time = datetime.strptime(event["start_time"], "%Y-%m-%d %H:%M:%S")
                        end_time = datetime.strptime(event["end_time"], "%Y-%m-%d %H:%M:%S")
                        dt = (end_time - start_time).total_seconds()
                        if dt < 300:
                            level = 1
                        elif dt < 1800:
                            level = 2
                        else:
                            level = 3
                        ddict = {
                            "startTime": event["start_time"],
                            "endTime": event["end_time"],
                            "direction": direction,
                            "eventType": "阻断",
                            "level": level
                        }
                        json_data["algorithmValue"].append(ddict)

                    json_data["version"] = "V2.1"
                    json.dump(json_data, f, ensure_ascii=False)
                    f.write("\n")

                time.sleep(0.1)


def deal_yongdu():
    json_folder = r'D:\GJ\项目\铜锣山\yongdu'
    json_path = r"D:\GJ\项目\事故检测\output0311\output11\readme.json"
    with open(json_path, mode='w', encoding='utf-8', newline='') as ff:
        for filename in os.listdir(json_folder):
            if filename.endswith('.json'):
                json_name = os.path.join(json_folder, filename)
                with open(json_name, mode='r', encoding='utf-8', newline='') as f:
                    json_data = json.load(f)
                    for data in json_data:
                        data["version"] = "V3.1"
                        json.dump(data, ff, ensure_ascii=False)
                        ff.write("\n")


if __name__ == "__main__":
    main2()
    # deal_yongdu()

    # true_json_path = r'C:\Users\wanji\Desktop\fsdownload\truth_0312.json'
    # new_true_json_path = r'C:\Users\wanji\Desktop\fsdownload\truth_0312_1.json'
    # with open(new_true_json_path, 'w', encoding='utf-8') as ffile:
    #     with open(true_json_path, 'r', encoding='utf-8') as file:
    #         for line in file:
    #             try:
    #                 data = json.loads(line)
    #                 ID = data["id"]
    #                 if ID[0:8] in ["20250124", "20250205", "20250206"]:
    #                     data["truthMark"] = ["未分类_1"]
    #                 json.dump(data, ffile, ensure_ascii=False)
    #                 ffile.write("\n")
    #             except Exception as e:
    #                 print(e)

